package com.microwintech.boardingtreasure.ui.boardpass;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.microwintech.boardingtreasure.R;
import com.microwintech.boardingtreasure.adapter.boardpass.BoardPassenger;
import com.microwintech.boardingtreasure.adapter.boardpass.BoardPassengerAdapter;
import com.microwintech.boardingtreasure.common.client.HttpPostManage;
import com.microwintech.boardingtreasure.common.client.VolleyBean;
import com.microwintech.boardingtreasure.common.client.VolleyInterface;
import com.microwintech.boardingtreasure.common.client.VolleyManage;
import com.microwintech.boardingtreasure.common.dialog.ConfirmCancelDialog;
import com.microwintech.boardingtreasure.common.dialog.ConfirmCancelInterface;
import com.microwintech.boardingtreasure.common.lang.Constant;
import com.microwintech.boardingtreasure.db.bean.UserInfo;
import com.microwintech.boardingtreasure.db.cache.UserCache;
import com.microwintech.boardingtreasure.ui.flightdynamic.FlightQueryActivity;
import com.microwintech.boardingtreasure.util.DateUtil;
import com.microwintech.boardingtreasure.util.StringUtil;
import com.microwintech.boardingtreasure.util.ToastUtil;
import com.microwintech.platform.common.companent.customcalendar.CalendarInterface;
import com.microwintech.platform.common.companent.customcalendar.CalendarPopupWindow;
import com.microwintech.platform.common.companent.effectsbutton.EffectsButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2014/10/30.
 * 办理登机牌
 */
public class BoardingPassActivity extends Activity {
    private EditText flightNumberEt;
    private TextView dateEt;//航班号
    private List<BoardPassenger> passengerList;
    private ListView contactLv;
    private UserInfo userInfo;
    private ConfirmCancelDialog comCalDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.boarding_pass);
        
        LinearLayout backLl = (LinearLayout) findViewById(R.id.common_top_back_ll);
        backLl.setOnClickListener(new FinishClickListener());
        Intent intent = getIntent();
        String flight_code = intent.getStringExtra("flight_code");
        String flight_date = intent.getStringExtra("flight_date");
        String flight_data = intent.getStringExtra("flight_data");
        flightNumberEt = (EditText) findViewById(R.id.boarding_pass_flight_number_et);
        flightNumberEt.setText(flight_code);
//        EffectsButton searchEb = (EffectsButton) findViewById(R.id.boarding_pass_search_flight_btn);
//        searchEb.setOnClickListener(new SearchClickListener());
        dateEt = (TextView) findViewById(R.id.boarding_pass_date_et);
        dateEt.setText(flight_date);
        dateEt.setOnClickListener(new TimeClickListener());
        EffectsButton passChooseEb = (EffectsButton) findViewById(R.id.boarding_pass_choose_rl);
        passChooseEb.setOnClickListener(new PassengerClickListener('P'));
        EffectsButton newContactEb = (EffectsButton) findViewById(R.id.boarding_pass_new_contact_rl);
        newContactEb.setOnClickListener(new PassengerClickListener('N'));
        EffectsButton handleEb = (EffectsButton) findViewById(R.id.boarding_pass_handle_rl);
        handleEb.setOnClickListener(new HandleClickListener());
        contactLv = (ListView) findViewById(R.id.boarding_pass_lv);
        passengerList = new ArrayList<BoardPassenger>();
        userInfo = UserCache.getInstance().getUser(BoardingPassActivity.this);
        if ("data".equals(flight_data)) {
            BoardPassenger board = new BoardPassenger();
            board.setName(userInfo.getName());
            board.setPhone(userInfo.getPhoneNumber());
            board.setCardNumber(userInfo.getCardNo());
            board.setPreferArea(userInfo.getPreferArea());
            board.setPreferSeat(userInfo.getPreferSeat());
            board.setStatus("False");
            passengerList.add(board);
        } else {
            dateEt.setText(DateUtil.getDateNow());
        }
        refreshData(passengerList);
    }

    class FinishClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            finish();
        }
    }

    private void refreshData(List<BoardPassenger> passengerList) {
        BoardPassengerAdapter boardAdapter = new BoardPassengerAdapter(this, passengerList, new DeleteSelectBoard());
        contactLv.setAdapter(boardAdapter);
    }

    class PassengerClickListener implements View.OnClickListener {
        char type;

        PassengerClickListener(char type) {
            this.type = type;
        }

        @Override
        public void onClick(View v) {
            switch (type) {
                case 'P': {
                    Intent hotIntent = new Intent(BoardingPassActivity.this, PassengerChooseActivity.class);
                    hotIntent.putExtra("passengerJson", JSON.toJSONString(passengerList));
                    startActivityForResult(hotIntent, Constant.ACT_RES_BOARDING_PASS_CHOOSE_CODE);
                    break;
                }
                case 'N': {
                    Intent hotIntent = new Intent(BoardingPassActivity.this, AddUpPassengerActivity.class);
                    hotIntent.putExtra("passengerJson", JSON.toJSONString(passengerList));
                    startActivityForResult(hotIntent, Constant.ACT_RES_BOARDING_ADDUP_PASS_CODE);
                    break;
                }
            }
        }
    }


    class TimeClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            new CalendarPopupWindow(BoardingPassActivity.this, dateEt, new GainCalendar());
        }
    }

    class HandleClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            String flightNumber = flightNumberEt.getText().toString();
            String date = dateEt.getText().toString();
            if (StringUtil.isBlank(flightNumber)) {
                Toast.makeText(BoardingPassActivity.this, "请您输入航班号", Toast.LENGTH_SHORT).show();
                return;
            }
            if (StringUtil.isBlank(date)) {
                Toast.makeText(BoardingPassActivity.this, "请您选择航班时间", Toast.LENGTH_SHORT).show();
                return;
            }
            if (passengerList.size() < 1) {
                Toast.makeText(BoardingPassActivity.this, "请您选择乘机人", Toast.LENGTH_SHORT).show();
                return;
            }
            new UploadTask().execute();

        }
    }

    class UploadTask extends AsyncTask<String, String, VolleyBean> {

        @Override
        protected VolleyBean doInBackground(String... params) {
            Map<String, Object> mapParam = new HashMap<String, Object>();
            String flightNumber = flightNumberEt.getText().toString();
            String date = dateEt.getText().toString();
            mapParam.put("FlightCode", flightNumber);
            mapParam.put("FlightDate", date);
            mapParam.put("UserGuid", userInfo.getUserGuid());
            JSONArray parArray = new JSONArray();
            for (BoardPassenger board : passengerList) {
                JSONObject obj = new JSONObject();
                obj.put("UserName", board.getName());
                obj.put("CardNo", board.getCardNumber());
                obj.put("MobilePhone", board.getPhone());
                obj.put("PreferArea", board.getPreferArea());
                obj.put("PreferSeat", board.getPreferSeat());
                obj.put("Status", board.getStatus());
//            "UserName": "陆士林",
//                    "CardNo": "320626196311254613",
//                    "MobilePhone": "13706285177",
//                    "PreferArea": "",
//                    "PreferSeat": "",
//                    "Status": "True"
                parArray.add(obj);
            }
            mapParam.put("UserDetail", parArray);
            return HttpPostManage.getInstance().methodPost(BoardingPassActivity.this, mapParam);
        }

        @Override
        protected void onPostExecute(VolleyBean volleyBean) {
            super.onPostExecute(volleyBean);
            if (volleyBean.isSuccess()) {
                Intent intent = new Intent(BoardingPassActivity.this, BoardingPassResultActivity.class);
                JSONArray parArray = new JSONArray();
                for (BoardPassenger board : passengerList) {
                    JSONObject obj = new JSONObject();
                    obj.put("UserName", board.getName());
                    obj.put("CardNo", board.getCardNumber());
                    obj.put("MobilePhone", board.getPhone());
                    parArray.add(obj);
                }
                intent.putExtra("passengerJSONArray", parArray.toJSONString());
                intent.putExtra("orderJson", volleyBean.getContent());
                startActivity(intent);
            } else {
                comCalDialog = new ConfirmCancelDialog(BoardingPassActivity.this, volleyBean.getContent(), true, new ConfirmCancelReal());
                comCalDialog.show();
            }
//            Intent intent = new Intent(BoardingPassActivity.this, BoardingPassResultActivity.class);
//            JSONArray parArray = new JSONArray();
//            for (BoardPassenger board : passengerList) {
//                JSONObject obj = new JSONObject();
//                obj.put("UserName", board.getName());
//                obj.put("CardNo", board.getCardNumber());
//                obj.put("MobilePhone", board.getPhone());
//                parArray.add(obj);
//            }
//            intent.putExtra("passengerJSONArray", parArray.toJSONString());
//            intent.putExtra("orderJson", "{\"OrderID\":\"12345\",\"CityOpenStatus\":\"True\",\"NeedPayMent\":\"True\",\"Airport\":\"上海虹桥-北京首都\"}");
//            String flightNumber = flightNumberEt.getText().toString().trim();
//            String date = dateEt.getText().toString().trim();
//            intent.putExtra("flight_number", flightNumber);
//            intent.putExtra("flight_date", date);
//            startActivity(intent);
        }
    }


    class ConfirmCancelReal implements ConfirmCancelInterface {

        @Override
        public void handleClick(boolean click) {
            comCalDialog.dismiss();
        }
    }


    class SearchClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            String flightNumber = flightNumberEt.getText().toString();
            if (StringUtil.isNotBlank(flightNumber)) {
                Intent intent = new Intent(BoardingPassActivity.this, FlightQueryActivity.class);
                intent.putExtra("flightNumber", flightNumber);
                intent.putExtra("searchType", "number");
                startActivity(intent);
            } else {
                ToastUtil.TextToast(BoardingPassActivity.this, "请您输入航班号", Toast.LENGTH_SHORT);
            }
        }
    }

    class DeleteSelectBoard implements BoardPassInterface {

        @Override
        public void gainBoardResult(BoardPassenger board) {
            passengerList.remove(board);
            refreshData(passengerList);
        }
    }

    class GainCalendar implements CalendarInterface {

        @Override
        public void gainSelectedDate(String selectDate, String weekDay) {
            dateEt.setText(selectDate);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case Constant.ACT_RES_BOARDING_PASS_CHOOSE_CODE: {
                    //常用乘机人选择
                    String passArrayStr = data.getStringExtra("passengerArray");
                    JSONArray parArray = JSON.parseArray(passArrayStr);
                    int count = parArray.size();
                    for (int i = 0; i < count; i++) {
                        JSONObject obj = parArray.getJSONObject(i);
                        BoardPassenger board = new BoardPassenger();
                        board.setName(obj.getString("name"));
                        board.setPhone(obj.getString("phone"));
                        board.setCardNumber(obj.getString("cardNumber"));
                        board.setPreferArea(obj.getString("PreferArea"));
                        board.setPreferSeat(obj.getString("PreferSeat"));
                        board.setStatus(obj.getString("Status"));
                        boolean isNoExist = true;
                        for (BoardPassenger pass : passengerList) {
                            if (board.getCardNumber().equals(pass.getCardNumber())) {
                                isNoExist = false;
                            }
                        }
                        if (isNoExist) {
                            passengerList.add(board);
                        }
                    }

                    refreshData(passengerList);
                    break;
                }
                case Constant.ACT_RES_BOARDING_ADDUP_PASS_CODE: {
                    //添加乘机人
                    BoardPassenger board = new BoardPassenger();
                    board.setName(data.getStringExtra("name"));
                    board.setPhone(data.getStringExtra("phone"));
                    board.setCardNumber(data.getStringExtra("cardNumber"));
                    board.setCardNumber(data.getStringExtra("cardNumber"));
                    board.setPreferArea(data.getStringExtra("PreferArea"));
                    board.setPreferSeat(data.getStringExtra("PreferSeat"));
                    board.setStatus(data.getStringExtra("Status"));
                    passengerList.add(board);
                    refreshData(passengerList);
                    break;
                }
            }
        }

    }

}
